/*


 */

package jas.rpc.server;

import jas.rpc.*;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

/**
 *
 *
 */
public class RpcServerObjectOutputStream extends ObjectOutputStream {
    
    private ObjectIdBank ids;
    
    public RpcServerObjectOutputStream(OutputStream output, ObjectIdBank ids) throws IOException {
        super(output);
        this.ids = ids;
        enableReplaceObject(true);
    }
    
    private boolean debug = false;
    
    public void setDebug(boolean d) {
        debug = d;
    }
    
    private Class getRemoteClass(Class c) {
        if (c == null)
            return null;
        Class[] interfaces = c.getInterfaces();
        for (Class inte : interfaces) {
            if (inte == Remote.class)
                return c;
        }
        for (Class inte : interfaces) {
            Class remote = getRemoteClass(inte);
            if (remote != null)
                return remote;
        }
        return null;
    }
    
    @Override
    protected final Object replaceObject(Object obj) throws IOException {
        if (obj instanceof Remote) {
            String id = ids.getId(obj);
            Class remoteClass = getRemoteClass(obj.getClass());
            RemoteObject r = new RemoteObject(remoteClass, id);
            if (debug) {
                System.out.println("Printing: " + r);
            }
            return r;
        }
        if (debug) {
            System.out.println("Printing: " + obj);
        }
        return obj;
    }
    
}
